import * as PIXI from 'pixi.js'
import useMainStore from '@renderer/store/modules/useMainStore'
import { nameCard } from '@renderer/config'
import useDiyStore from '@renderer/store/modules/useDiyStore'

export const pixiToBase64 = async (target: PIXI.ContainerChild | PIXI.Texture): Promise<string> => {
  const app = await useMainStore().getApp()
  return await app.renderer.extract.base64(target)
}

export const exportCard = async (target: PIXI.ContainerChild, name: string = '五行师'): Promise<void> => {
  const img = await pixiToBase64(target)

  const download = document.createElement('a')
  download.href = img
  download.download = name
  download.click()
  download.remove()
}

export const exportJson = async (data: Wx.Card.Data, name?: string): Promise<void> => {
  const diyStore = useDiyStore()
  const exportData = diyStore.dataCompleted()
  if (!exportData.picture) {
    if (exportData.isDiy && diyStore.editCardId !== -1) {
      const assets = await PIXI.Assets.load<PIXI.Texture>('card_' + diyStore.editCardId) // 资源加载
      exportData.picture = await pixiToBase64(assets)
    } else {
      exportData.picture = await window.api.assetsDataUrl(nameCard(data)) // TODO 这里的卡牌ID是动态的
    }
  }
  const jsonData = JSON.stringify(exportData, null, 2)
  const blob = new Blob([jsonData], { type: 'application/json' })
  const url = URL.createObjectURL(blob)
  const download = document.createElement('a')
  download.href = url
  download.download = (name || data.name || '五行师') + '.json'
  download.click()
  download.remove()
  URL.revokeObjectURL(url)
}
